package com.urerp.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.urerp.web.common.CommonUtil;
import com.urerp.web.common.SessionUtil;
import com.urerp.web.persistence.CodeMapper;
import com.urerp.web.persistence.MemberMapper;

@Controller
public class MemberController {
	
	private static final Logger logger = LogManager.getLogger(MemberController.class); 

	@Autowired
	private MemberMapper memberMapper;	
	
	@Autowired
	private CodeMapper codeMapper;
	
	// 프로퍼티 파일 읽기
	@Value("#{code['member.pos']}") 			private String m_pos;
    @Value("#{code['member.status']}")			private String m_status;
    @Value("#{code['member.status.normal']}")	private String m_status_normal;
    @Value("#{code['member.status.out']}")		private String m_status_out;
    @Value("#{code['auth.level']}")				private String m_level;
    
    // 직원 리스트
    @RequestMapping(value = "/member/list")
	public String list(Model model, @RequestParam HashMap<String, String> keywordMap) {
    	
    	logger.debug("RequestMapping : /member/list, Method : list");
    	
    	// 상태 정보
    	model.addAttribute("statusList", codeMapper.getGroupCodeList(m_status));
    	
    	return "/member/list";
    }
    
    // 직원 리스트 데이터
    @RequestMapping(value = "/member/listData", method = RequestMethod.GET, produces = "application/json; charset=utf8")
	public @ResponseBody HashMap<String, Object> listData(Model model, @RequestParam HashMap<String, Object> tableMap) {
    	
    	logger.debug("RequestMapping : /member/listData, Method : listData");
    	
    	
    	if (tableMap != null) {
    		tableMap.put("M_POS", 		m_pos);
    		tableMap.put("M_STATUS",	m_status);
    		tableMap.put("M_LEVEL", 	m_level);
    	}
    	
    	tableMap.put("order_by", tableMap.get("mDataProp_" + tableMap.get("iSortCol_0")) + " " + tableMap.get("sSortDir_0"));
    	
    	ArrayList<LinkedHashMap<String, String>> list = memberMapper.getMemberList(tableMap);

    	tableMap.put("sEcho", 					Integer.parseInt((String) tableMap.get("sEcho")));
    	tableMap.put("iTotalRecords", 			memberMapper.getMemberListCount(tableMap));
    	tableMap.put("iTotalDisplayRecords", 	tableMap.get("iTotalRecords"));
    	tableMap.put("aaData", 					list);

    	return tableMap;
    }
    
    // 직원 등록 폼
    @RequestMapping(value = "/member/registerForm")
	public String registerForm(Model model) {
    	
    	logger.debug("RequestMapping : /member/registerForm, Method : registerForm");
    	
    	// 직급 정보
    	model.addAttribute("posList", codeMapper.getGroupCodeList(m_pos));
    	
    	// 레벨 정보
    	model.addAttribute("levelList", codeMapper.getGroupCodeList(m_level));
    	
    	// 상태 정보
    	model.addAttribute("statusList", codeMapper.getGroupCodeList(m_status));
    	
    	return "member/register_form";
    }
    
    // 직원 상세(수정) 폼
    @RequestMapping(value = "/member/modifyForm", method = RequestMethod.POST)
	public String modifyForm(Model model, @RequestParam HashMap<String, String> memberMap) {
    	
    	logger.debug("RequestMapping : /member/modifyForm, Method : modifyForm");
    	
    	// 직급 정보
    	model.addAttribute("posList", codeMapper.getGroupCodeList(m_pos));
    	
    	// 레벨 정보
    	model.addAttribute("levelList", codeMapper.getGroupCodeList(m_level));
    	
    	// 상태 정보
    	model.addAttribute("statusList", codeMapper.getGroupCodeList(m_status));
    	
    	memberMap.put("M_POS",		m_pos);
    	memberMap.put("M_STATUS",	m_level);
    	memberMap.put("M_LEVEL", 	m_status);
    	memberMap = memberMapper.getMemberInfoPassPassword(memberMap);
    	
    	model.addAttribute("memberMap", memberMap);    	
    	
    	return "member/register_form";
    }
    
    // 직원 아이디 중복 체크
    @RequestMapping(value = "/member/memberDuplicateCheck")
    public @ResponseBody String memberDuplicateCheck(HttpServletResponse response, @RequestParam String user_id) {
    	
    	if (user_id == null) {
    		response.setStatus(400);
    		return "400";
    	}
    	
    	if (memberMapper.getMemberDuplicateCheck(user_id) > 0) {
    		 response.setStatus(406);
    		 return "406";
    	}
    	
    	response.setStatus(200);
    	return "200";
    }
    
    // 직원 등록/수정 (DB Insert/Update)
    @RequestMapping(value = {"/member/submitRegister","/member/submitModify"}, method = RequestMethod.POST, produces = "application/json; charset=utf8")
    public @ResponseBody String submit(Model model, HttpServletRequest request, @RequestParam HashMap<String, String> memberMap) {
    	
    	logger.debug("RequestMapping : {}, Method : submit", request.getServletPath());
    	
    	/*
    	 * 오류코드
    	 * 0 - success
    	 * 9 - no data
    	 * 1 - db insert / update failed
    	 * 8 - exception
    	 */
    	
    	if (memberMap == null) {
    		return "9";
    	}
    	
    	int result = 0;
    	
    	// 등록(수정)자 가져와서 넣기
    	if (memberMap.get("docu_type").equals("W")) {
    		memberMap.put("reg_user", SessionUtil.getMemberSession("USER_ID"));
    		
    		result = memberMapper.setMember(memberMap);
    		
    	} else if (memberMap.get("docu_type").equals("M")) {
    		memberMap.put("upd_user", SessionUtil.getMemberSession("USER_ID"));
    		
    		if (CommonUtil.isNotEmpty(memberMap.get("out_date"))) {
    			memberMap.put("out_status", m_status_out);
    		}
    		
    		if (memberMapper.getOutDate(memberMap.get("user_id")) != null && memberMap.get("status").equals(m_status_normal)) {
    			memberMap.put("out_date", null);
    		}
    		
    		result = memberMapper.updateMember(memberMap);
    	}
    	
    	try {
    		
    		if (result != 1) {
    			
    			return "1";
    		}
    		
    	} catch (Exception e) {
    		logger.debug("setMember : Insert or Modify Fail - {}", e.getMessage());
    		
    		return "8";
    	}
    	
    	return "0";
    }
    
 // 직원 삭제 (DB Delete)
    @RequestMapping(value = "/member/submitDelete", method = RequestMethod.POST, produces = "application/json; charset=utf8")
    public @ResponseBody String submitDelete(Model model, @RequestParam HashMap<String, String> memberMap) {
    	
    	logger.debug("RequestMapping : submitDelete, Method : submit");
    	
    	/*
    	 * 오류코드
    	 * 0 - success
    	 * 9 - no data
    	 * 1 - db delete failed
    	 * 8 - exception
    	 */
    	
    	if (memberMap == null) {
    		return "9";
    	}
    	
    	int result = 0;
    	
    	// 삭제자 가져와서 넣기
		memberMap.put("upd_user", SessionUtil.getMemberSession("USER_ID"));
		
		result = memberMapper.deleteMember(memberMap);
    	
    	try {
    		
    		if (result != 1) {
    			
    			return "1";
    		}
    		
    	} catch (Exception e) {
    		logger.debug("setMember : Delete Fail - {}", e.getMessage());
    		
    		return "8";
    	}
    	
    	return "0";
    }
}
